package com.dorso.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dorso.entity.Supplier;
import com.dorso.exception.ProductAdminException;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dorso.dao.ProductDao;
import com.dorso.entity.Product;
import com.dorso.service.ProductService;
import org.apache.catalina.util.Introspection;

import java.util.Map;
@Service
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product>implements ProductService {
    @Override
    public IPage<Product>findProduct(Map<String,Object>condition, Integer pageNum,Integer pageSize){
        Page<Product>page=new Page<>(pageNum,pageSize);
        QueryWrapper<Product>queryWrapper=new QueryWrapper<>();
        queryWrapper.like(condition.containsKey("name"),"p.name",condition.get("name"));
        queryWrapper.le(condition.containsKey("price"), "p.price", condition.get("price"));
        queryWrapper.ge(condition.containsKey("num"), "p.num", condition.get("num"));
        if(condition.containsKey("supplierName")){
            queryWrapper.eq("s.name", condition.get("supplierName"));
            this.baseMapper.findProductsBySupplier(page, queryWrapper); //多表查询
        }else{
            this.baseMapper.findProducts(page, queryWrapper); //单表查询
        }
        return page;}
    @Override
    @Transactional
    public Product addProduct(Product product)throws ProductAdminException{
        try {
            this.baseMapper.insert(product);
            for (Supplier supplier : product.getSupplierList()) {
                this.baseMapper.insertProductSupplier(product.getId(), supplier.getId());
            }
            return product;
        }catch (Exception e) {
            throw new ProductAdminException("添加产品失败：" + e.getMessage());
        }
    }
    @Override
    public void updateProduct(long id, Product product) throws ProductAdminException {
        if (this.baseMapper.selectById(id) == null) {
            throw new ProductAdminException("产品" + id + "不存在");
        }
        try {
            this.baseMapper.updateById(product);
            this.baseMapper.deleteSupplierByProduct(product.getId());
            for (Supplier supplier : product.getSupplierList()) {
                this.baseMapper.insertProductSupplier(product.getId(), supplier.getId());
            }
        } catch (Exception e) {
            throw new ProductAdminException("修改产品失败：" + e.getMessage());
        }
    }

}
